package com.hk.kindheartedness;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.Date;

/**
 * 医生新增病历业务处理
 *
 */
public class DoctorAddCaseHistoryActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private TextView userNumber,userName,userAge,userSex,departmentsName;

    private EditText userMainSuit,userPhi,previousHistory,drugAllergyHistory,personalAndFamilyHistory,healthCheckup,auxiliaryExamination,tentativeDiagnosis;

    private String loginDoctorId,registrationLogId,userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_add_case_history);
//        实例化
        dbOpenHelper = new DBOpenHelper(DoctorAddCaseHistoryActivity.this, "db_kindheartedness", null, 1);
//        获取当前登录医生Id
        Intent intent2 = getIntent();
        final Bundle bundle = intent2.getExtras();
//        当前医生Id
        loginDoctorId = bundle.getString("loginDoctorId");
//        患者挂号Id
        registrationLogId = bundle.getString("registrationLogId");
//        获取按钮控制权
        Button addCaseHistoryBtn = findViewById(R.id.addCaseHistoryBtn);
        addCaseHistoryBtn.setOnClickListener(this);
//      获取各文本框和输入框控制权
        userNumber = findViewById(R.id.userNumber);
        userNumber.setText(randomString());
        userName = findViewById(R.id.userName);
        userAge = findViewById(R.id.userAge);
        userSex = findViewById(R.id.userSex);
        departmentsName = findViewById(R.id.departmentsName);
        userMainSuit = findViewById(R.id.userMainSuit);
        userPhi = findViewById(R.id.userPhi);
        previousHistory = findViewById(R.id.previousHistory);
        drugAllergyHistory = findViewById(R.id.drugAllergyHistory);
        personalAndFamilyHistory = findViewById(R.id.personalAndFamilyHistory);
        healthCheckup = findViewById(R.id.healthCheckup);
        auxiliaryExamination = findViewById(R.id.auxiliaryExamination);
        tentativeDiagnosis = findViewById(R.id.tentativeDiagnosis);

        /**
         * 1、通过患者挂号Id查询，获取患者Id
         * 2、通过患者Id查询患者姓名、性别、年龄、并进行回显，且不能修改
         * 2.1、通过医生Id获取所属科室Id，并查询出科室名称
         * 3、获取各输入框的控制权和内容，并进行校验
         * 4、新增病历
         */
//        ================== 1、==== 2、 ====================
        findByRegistrationLogId();




    }

    /**
     * 查询就诊患者基础信息并进行页面展示
     */
    private void findByRegistrationLogId() {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        通过患者挂号记录ID查询患者用户ID
        Cursor queryRegistrationLog = readableDatabase.query("registration_log", null, "id = ?", new String[]{registrationLogId}, null, null, null);
        userId = null;
        while (queryRegistrationLog.moveToNext()) {
            userId = queryRegistrationLog.getString(1);
        }
        if (userId == null) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"未查到患者就诊记录,请刷新重试！");
            return;
        }
//        通过用户Id查询用户基本信息
        Cursor queryUser = readableDatabase.query("user", null, "id = ?", new String[]{userId}, null, null, null);
        String userName2 = null;
        String sex = null;
        String age = null;
        while (queryUser.moveToNext()) {
            userName2 = queryUser.getString(1);
            sex = Integer.parseInt(queryUser.getString(6)) == 0 ? "男":"女";
            age = queryUser.getString(7);
        }
        if (userName2 == null || sex == null || age == null) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"未查到患者基础信息,请刷新重试！");
            return;
        }
//        通过医生Id查询医生所属科室Id，通过科室Id查询出科室名称
        Cursor query = readableDatabase.query("doctor_details", null, "id = ?", new String[]{loginDoctorId}, null, null, null);
        String departmentsId = null;
        while (query.moveToNext()) {
            departmentsId = query.getString(3);
        }
        if (departmentsId == null) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"所属科室不存在！");
            return;
        }
        Cursor queryDepartments = readableDatabase.query("departments", null, "id = ?", new String[]{departmentsId}, null, null, null);
        String departmentsName2 = null;
        while (queryDepartments.moveToNext()) {
            departmentsName2 = queryDepartments.getString(1);
        }
        userName.setText(userName2);
        userAge.setText(age);
        userSex.setText(sex);
        departmentsName.setText(departmentsName2);
    }

    /**
     * 随机用户编号
     * @return
     */
    private static String randomString() {
        String yyyyMMdd = DateUtil.dateString(new Date(), "yyyyMMdd");
        long l = System.currentTimeMillis();
        String s = String.valueOf(l).substring(9);
        return yyyyMMdd+s;
    }

    /**
     * 按钮点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            新增患者病历
            case R.id.addCaseHistoryBtn:
                addCaseHistory();
                break;
            default:
                break;
        }

    }

    /**
     * 新增患者病历
     */
    private void addCaseHistory() {
//        获取各文本框内容
        String userNumberToStr = userNumber.getText().toString();
        String userNameToStr = userName.getText().toString();
        String userAgeToStr = userAge.getText().toString();
        String userSexToStr = userSex.getText().toString();
        String departmentsNameToStr = departmentsName.getText().toString();
        String userMainSuitToStr = userMainSuit.getText().toString();
        String userPhiToStr = userPhi.getText().toString();
        String previousHistoryToStr = previousHistory.getText().toString();
        String drugAllergyHistoryToStr = drugAllergyHistory.getText().toString();
        String personalAndFamilyHistoryToStr = personalAndFamilyHistory.getText().toString();
        String healthCheckupToStr = healthCheckup.getText().toString();
        String auxiliaryExaminationToStr = auxiliaryExamination.getText().toString();
        String tentativeDiagnosisToStr = tentativeDiagnosis.getText().toString();
//        校验数据
        Boolean check = checkDate(
                userNumberToStr,userNameToStr,userAgeToStr,userSexToStr,departmentsNameToStr,
                userMainSuitToStr, userPhiToStr,previousHistoryToStr,drugAllergyHistoryToStr,personalAndFamilyHistoryToStr,
                healthCheckupToStr,auxiliaryExaminationToStr,tentativeDiagnosisToStr);
        if (check) {
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//            查询当前患者挂号记录病历是否已开具
            Cursor queryCaseHistory = readableDatabase.query("case_history", null, "registration_log_id = ?", new String[]{registrationLogId}, null, null, null);
            String caseHistoryId = null;
            while (queryCaseHistory.moveToNext()) {
                caseHistoryId = queryCaseHistory.getString(0);
            }
            if (caseHistoryId != null) {
                toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"病历已开具,请勿重新开具!");
                return;
            }
//            字段关系映射封装
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",userNameToStr);
            contentValues.put("user_number",userNumberToStr);
            contentValues.put("sex",userSexToStr);
            contentValues.put("age",userAgeToStr);
            contentValues.put("departments_name",departmentsNameToStr);
            contentValues.put("main_suit",userMainSuitToStr);
            contentValues.put("phi",userPhiToStr);
            contentValues.put("previous_history",previousHistoryToStr);
            contentValues.put("drug_allergy_history",drugAllergyHistoryToStr);
            contentValues.put("personal_and_family_history",personalAndFamilyHistoryToStr);
            contentValues.put("health_checkup",healthCheckupToStr);
            contentValues.put("auxiliary_examination",auxiliaryExaminationToStr);
            contentValues.put("tentative_diagnosis",tentativeDiagnosisToStr);
            contentValues.put("user_id",userId);
            contentValues.put("doctor_id",loginDoctorId);
            contentValues.put("registration_log_id",registrationLogId);
            contentValues.put("patient_name",userNameToStr);
            contentValues.put("create_time",DateUtil.dateString(new Date()));
            contentValues.put("update_time",DateUtil.dateString(new Date()));
            long insert = readableDatabase.insert("case_history", null, contentValues);
            if (insert > 0) {
                toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"病历保存成功!");
                return;
            }
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"病历保存失败,请重新保存！");
            return;
        }


    }

    /**
     * 校验各参数是否正确或不为空
     * @param userNumberToStr 患者编号
     * @param userNameToStr 患者姓名
     * @param userAgeToStr 患者年龄
     * @param userSexToStr 患者性别
     * @param departmentsNameToStr 患者挂诊科室
     * @param userMainSuitToStr 主诉
     * @param userPhiToStr 现病史
     * @param previousHistoryToStr 既往史
     * @param drugAllergyHistoryToStr 药物过敏史
     * @param personalAndFamilyHistoryToStr 个人及家族史
     * @param healthCheckupToStr 体格检查
     * @param auxiliaryExaminationToStr 辅助检查
     * @param tentativeDiagnosisToStr 初步诊断
     * @return 返回true表示校验成功
     */
    private Boolean checkDate(
            String userNumberToStr, String userNameToStr, String userAgeToStr, String userSexToStr,String departmentsNameToStr,
            String userMainSuitToStr, String userPhiToStr, String previousHistoryToStr,
            String drugAllergyHistoryToStr, String personalAndFamilyHistoryToStr,
            String healthCheckupToStr, String auxiliaryExaminationToStr, String tentativeDiagnosisToStr
    ) {
        if (userNumberToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"患者编号不能为空！");
            return false;
        }
        if (userNameToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"患者姓名不能为空！");
            return false;
        }
        if (userAgeToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"患者年龄不能为空！");
            return false;
        }
        if (userSexToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"患者性别不能为空！");
            return false;
        }
        if (departmentsNameToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"挂诊科室不能为空！");
            return false;
        }
//      校验各输入参数
        if (userMainSuitToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"主诉不能为空！");
            return false;
        }
        if (userPhiToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"现病史不能为空！");
            return false;
        }
        if (previousHistoryToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"既往史不能为空！");
            return false;
        }
        if (drugAllergyHistoryToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"药物过敏史不能为空！");
            return false;
        }
        if (personalAndFamilyHistoryToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"个人及家族史不能为空！");
            return false;
        }
        if (healthCheckupToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"体格检查不能为空！");
            return false;
        }
        if (auxiliaryExaminationToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"辅助检查不能为空！");
            return false;
        }
        if (tentativeDiagnosisToStr.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddCaseHistoryActivity.this,"初步诊断不能为空！");
            return false;
        }
        return true;
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}